package ltd.dujiabao.dex.quartz.exe;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.dex.core.DelayJobEntity;

/**
 * @author : DuJiabao
 * @Project : common-delay-executor
 * @Time : 2024/3/30 17:48
 * @Desc :
 */
@Slf4j
public class QuartzJob implements Job, BeanFactoryAware {
    private BeanFactory beanFactory;

    public QuartzJob() {
    }

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap jobDataMap = context.getMergedJobDataMap();

        Method method = (Method) jobDataMap.get("method");
        Object[] args = (Object[]) jobDataMap.get("args");
        DelayJobEntity delayJob = (DelayJobEntity) jobDataMap.get("delayJob");

        Object bean = beanFactory.getBean(delayJob.getImplementation());
        try {
            method.invoke(bean, args);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.info("error ", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
